<script setup>

import {getCurrentInstance, ref} from "vue";
import {changeSysJobStatus, deleteSysJob, listSysJob, runJob} from "@/api/monitor/sys_job";
import {jobGroupStatusList, jobStatusList} from "@/enum/enum";
import DictTag from "@/components/DictTag/index.vue";
import {enumToArray, hasPermission} from "@/utils/utils";
import SysJobForm from "@/views/monitor/task/SysJobForm.vue";
import SysJobDetailForm from "@/views/monitor/task/SysJobDetailForm.vue";
import {router} from "@/router";

const {proxy} = getCurrentInstance();
const sysJobList = ref([]);
const total = ref(0);
const ids = ref([])
const queryFormRef = ref();
const queryForm = ref({
  pageNo: 1,
  pageSize: 10,
  jobName: null,
  jobGroup: null,
  status: null
})
const sysJobFormRef = ref();
const sysJobDetailFormRef = ref();

const handleQuery = () => {
  queryForm.value.pageNo = 1;
  getList();
}

const handleReset = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const getList = async () => {
  const {data} = await listSysJob(queryForm.value)
  total.value = data.total;
  sysJobList.value = data.list;
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.jobId);
}

const handleChangeJobStatus = (jobId, value) => {
  let formData = {
    jobId,
    status: value
  };
  proxy.$modal.confirm(`确认${value === 0 ? '暂停' : '开启'}任务${jobId}吗？`).then(async () => {
    await changeSysJobStatus(formData);
    proxy.$modal.okNotify(`${value === 0 ? '暂停' : '开启'}成功`);
    await getList();
  })
}

const handleAdd = () => {
  sysJobFormRef.value.open();
}

const handleUpdate = () => {
  let id = ids.value[0];
  openSysJob(id, 'update');
}

const handleDelete = () => {
  let jobIds = ids.value;
  deleteSysJobs(jobIds);
}

const openSysJob = (jobId, type) => {
  sysJobFormRef.value.open(jobId, type)
}

const deleteSysJobs = (jobId) => {
  console.log(jobId)
  proxy.$modal.confirm('确定删除选中的定时任务吗?').then(async () => {
    await deleteSysJob(jobId);
    proxy.$modal.okNotify('删除成功');
    await getList();
  })
}

const handleCommand = (command, row) => {
  switch (command) {
    case "handleRun":
      handleRun(row);
      break;
    case "handleDetail":
      handleDetail(row);
      break;
    case "handleJobLog":
      handleJobLog(row);
      break;
  }
}

const handleRun = (row) => {
  proxy.$modal.confirm(`确认要立即执行一次${row.jobName}任务吗？`).then(async () => {
    await runJob(row.jobId, row.jobGroup);
    proxy.$modal.okNotify('执行成功');
    await getList();
  })
}

const handleDetail = (row) => {
  sysJobDetailFormRef.value.open(row.jobId);
}

const handleJobLog = (row) => {
  const jobId = row.jobId || 0;
  router.push({
    path: '/task_log',
    query: {
      jobId: jobId
    }
  });
}

getList();
</script>

<template>
  <div class="app-container">

    <el-form :model="queryForm" ref="queryFormRef" :inline="true" class="demo-form-inline">
      <el-form-item label="任务名称" prop="jobName">
        <el-input v-model="queryForm.jobName" placeholder="请输入任务名称"/>
      </el-form-item>
      <el-form-item label="任务组名" prop="jobGroup">
        <el-select v-model="queryForm.jobGroup" placeholder="请选择任务组名">
          <el-option v-for="(item, index) in jobGroupStatusList" :key="index" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryForm.status" placeholder="请选择任务状态">
          <el-option v-for="(item, index) in jobStatusList" :key="index" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <icon icon="ep-search" size="14px" color="unset" class="mr-1"/>
          查询
        </el-button>
        <el-button plain @click="handleReset">
          <icon icon="ep-refresh" size="14px" color="unset" class="mr-1"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="flex mb-5">
      <el-button size="default" type="primary" plain class="flex items-center" @click="handleAdd"
                 v-hasPermission="['system:task:add']">
        <icon icon="ep-plus" size="14px" color="unset" class="mr-1"/>
        新增
      </el-button>
      <el-button size="default" type="success" plain :disabled="ids.length !== 1" class="flex items-center"
                 @click="handleUpdate" v-hasPermission="['system:task:edit']">
        <icon icon="ep-edit" size="14px" color="unset" class="mr-1"/>
        修改
      </el-button>
      <el-button size="default" type="danger" plain :disabled="!ids.length" class="flex items-center"
                 @click="handleDelete" v-hasPermission="['system:task:delete']">
        <icon icon="ep-delete" size="14px" color="unset" class="mr-1"/>
        删除
      </el-button>
      <el-button size="default" type="info" plain class="flex items-center" @click="handleJobLog"
                 v-hasPermission="['system:task:detail']">
        <icon icon="ep-setting" size="14px" color="unset" class="mr-1"/>
        日志
      </el-button>
    </div>

    <el-table :data="sysJobList" :border="true" size="large" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="jobId" label="任务编号"/>
      <el-table-column prop="jobName" label="任务名称"/>
      <el-table-column prop="jobGroup" label="任务组名">
        <template #default="scope">
          <dict-tag :options="enumToArray(jobGroupStatusList)" :value="scope.row.jobGroup"/>
        </template>
      </el-table-column>
      <el-table-column prop="invokeTarget" label="调用目标字符串" show-overflow-tooltip/>
      <el-table-column prop="cronExp" label="cron执行表达式"/>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
              @change="(value) => handleChangeJobStatus(scope.row.jobId,value)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200px">
        <template #default="scope">
          <div class="flex items-center">
            <el-button class="ml-2" type="primary" link @click="openSysJob(scope.row.jobId,'update')"
                       v-hasPermission="['system:task:edit']">编辑
            </el-button>
            <el-button class="ml-2" type="danger" link @click="deleteSysJobs(scope.row.jobId)"
                       v-hasPermission="['system:task:delete']">
              删除
            </el-button>
            <el-dropdown class="dropdown" @command="(command) => handleCommand(command,scope.row)"
                         v-if="hasPermission(['system:task:run','system:task:detail'])">
              <el-button link type="info" class="ml-2 more-btn">
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="hasPermission(['system:task:run'])" command="handleRun">执行一次
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['system:task:detail'])" command="handleDetail">任务详情
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['system:task:log'])" command="handleJobLog">调度日志
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNo"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"/>

    <sys-job-form ref="sysJobFormRef" @success="getList"/>
    <sys-job-detail-form ref="sysJobDetailFormRef" @success="getList"/>
  </div>
</template>

<style scoped lang="scss">
.dropdown {

  .more-btn {
    cursor: pointer;

    &:focus {
      outline: unset;
    }
  }
}
</style>
